/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.compiler.support;

import com.aduib.boot.common.compiler.AbstractCompiler;
import com.aduib.boot.common.compiler.JavaPattern;
import com.aduib.boot.common.util.ClassUtils;
import com.aduib.boot.common.util.IOUtils;
import com.aduib.boot.common.util.StrUtils;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.implementation.FixedValue;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import java.util.regex.Matcher;

/**
 * @description: JavassistClassBuilder
 * @author: zzh
 * @date: 2021/10/15 15:57
 */
@Deprecated
public class ByteBuddyCompiler extends AbstractCompiler {

  @Override
  public Class<?> doCompile(String name, String source) throws Throwable {
    ByteBuddyClassBuilder builder = new ByteBuddyClassBuilder();
    builder.setClassName(name);
    // 导入
    Matcher matcher = JavaPattern.IMPORT_PATTERN.matcher(source);
    while (matcher.find()) {
      builder.addImports(matcher.group(1).trim());
    }
    // 继承
    matcher = JavaPattern.EXTENDS_PATTERN.matcher(source);
    if (matcher.find()) {
      String trim = matcher.group(1).trim();
      System.out.println("#1" + trim);
      builder.setSuperClass(ClassUtils.forName(trim, ClassUtils.getDefaultClassLoader()));
    }

    matcher = JavaPattern.IMPLEMENTS_PATTERN.matcher(source);
    String[] ifaces = null;
    if (matcher.find()) {
      ifaces = matcher.group(1).trim().split("\\,");
    }
    if (Objects.nonNull(ifaces)) {
      for (String iface : ifaces) {
        System.out.println("#2" + iface);
        builder.addInterface(ClassUtils.forName(iface.trim(), ClassUtils.getDefaultClassLoader()));
      }
    }

    String body = source.substring(source.indexOf('{') + 1, source.length() - 1);
    String[] methods = JavaPattern.METHODS_PATTERN.split(body);
    String className = ClassUtils.getSimpleClassName(name);
    Arrays.stream(methods)
        .map(String::trim)
        .filter(m -> !m.isEmpty())
        .forEach(
            method -> {
              try {
                System.out.println("#3" + method);
                if (method.startsWith(className)) {
                  builder.addConstructorDescriptor(
                      builder
                          .buildConstructorDescriptor()
                          .setModifier(Visibility.PUBLIC)
                          .addParameterType(Object.class)
                          .addThrowable(Exception.class)
                          .setImplementation(
                              FixedValue.value(
                                  method.substring(method.indexOf('{') + 1, method.length() - 1))));
                } else if (JavaPattern.FIELD_PATTERN.matcher(method).matches()) {
                  String[] Allfields = method.split("=");
                  String[] fieldTypes = Allfields[0].split("\\s");
                  builder.addFieldDescriptor(
                      builder
                          .buildFieldDescriptor()
                          .setFieldName(fieldTypes[1])
                          .setModifier(Visibility.PRIVATE)
                          .setFieldType(
                              ClassUtils.forName(
                                  fieldTypes[0],
                                  ClassUtils.getDefaultClassLoader(ByteBuddyCompiler.class))));
                } else {
                  //                  builder.addMethod("public " + method);
                  String methodSig = method.substring(0, method.indexOf('('));
                  String[] methodSigs = methodSig.split("\\s");
                  Class<?> importsClass = builder.getImportsClass(methodSigs[0]);
                  if (Objects.isNull(importsClass)) {
                    importsClass = ClassUtils.classForName(methodSigs[0]);
                  }
                  builder.addMethodDescriptor(
                      (ByteBuddyClassBuilder.MethodDescriptor)
                          builder
                              .buildMethodDescriptor()
                              .setMethodName(methodSigs[1])
                              .setReturnType(importsClass)
                              .setModifier(Visibility.PUBLIC)
                              .addParameterType(Object.class)
                              .addThrowable(Exception.class)
                              .setImplementation(
                                  FixedValue.value(
                                      method.substring(
                                          method.indexOf('{') + 1, method.length() - 1))));
                }
              } catch (ClassNotFoundException ignored) {
              }
            });

    ClassLoader classLoader = ClassUtils.getDefaultClassLoader(ByteBuddyCompiler.class);
    //    CtClass cls = builder.build(classLoader);
    //    return cls.toClass(classLoader, ByteBuddyCompiler.class.getProtectionDomain());
    return builder.build(classLoader);
  }

  @Override
  protected Class<?> doCompile(byte[] code, String source) throws Throwable {
    return doCompile(StrUtils.str(code, StandardCharsets.UTF_8), source);
  }

  @Override
  protected Class<?> doCompile(InputStream inputStream, String source) throws Throwable {
    return doCompile(IOUtils.readBytes(inputStream), source);
  }
}
